﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

public class FightManager
{
    /// <summary>
    /// 最大回合数
    /// </summary>
    public static readonly int MAX_BOUT_COUNT = 20;

    private static readonly int[] DefaultRule = new int[] {0,1,2,0,1,1};

    /// <summary>
    /// 阵营1
    /// </summary>
    private readonly FightItem[] rightTeam = new FightItem[ConfigUtil.FIGHT_MEMBER_COUNT];
    /// <summary>
    /// 阵营2
    /// </summary>
    private readonly FightItem[] leftTeam = new FightItem[ConfigUtil.FIGHT_MEMBER_COUNT];

    /// <summary>
    ///  总回合数
    /// </summary>
    public int BoutCount { get; private set; }

    /// <summary>
    /// 记录
    /// </summary>
    public List<FightRecordItem> FightRecords { get; private set; }

    public FightManager()
    {
        FightRecords = new List<FightRecordItem>();
        Init();
    }

    public void Init()
    {
        for (int i = 0; i < rightTeam.Length; i++)
        {
            rightTeam[i] = null;
        }

        for (int i = 0; i < leftTeam.Length; i++)
        {
            leftTeam[i] = null;
        }
        FightRecords.Clear();
        BoutCount = 1;
    }

    public void Run()
    {
        for (int i=0; i<MAX_BOUT_COUNT; i++)
        {
            if (HandleBoutFight())
            {
                break;
            }
            BoutCount++;
        }
    }

    public void AddRightTeam(FightItem fightItem, int index = -1)
    {
        if (index > -1 && index < rightTeam.Length)
        {
            rightTeam[index] = fightItem;
            fightItem.Idx = index;
            fightItem.TeamType = TeamType.Right;
        }
        else
        {
            for (int i = 0; i < rightTeam.Length; i++)
            {
                if (rightTeam[i] == null)
                {
                    rightTeam[i] = fightItem;
                    fightItem.Idx = i;
                    fightItem.TeamType = TeamType.Right;
                    break;
                }
            }
        }
    }

    public void AddLeftTeam(FightItem fightItem, int index = -1)
    {
        if (index > -1 && index < leftTeam.Length)
        {
            leftTeam[index] = fightItem;
            fightItem.Idx = index;
            fightItem.TeamType = TeamType.Left;
        }
        else
        {
            for (int i = 0; i < leftTeam.Length; i++)
            {
                if (leftTeam[i] == null)
                {
                    leftTeam[i] = fightItem;
                    fightItem.Idx = i;
                    fightItem.TeamType = TeamType.Left;
                    break;
                }
            }
        }
    }

    private bool HandleBoutFight()
    {
        for (int i = 0; i < ConfigUtil.FIGHT_MEMBER_COUNT; i++)
        {
            if (HandleOneFight(leftTeam, rightTeam, leftTeam[i]) 
                || HandleOneFight(rightTeam, leftTeam, rightTeam[i]) )
            {
                return true;
            }
        }

        return false;
    }

    private bool HandleOneFight(FightItem[] atkTeam, FightItem[] defTeam, FightItem atk)
    {
        if (atk == null || atk.isDie())
        {
            return false;
        }

        FightRecordItem fightRecord;
        if (atk.isUseSkill())
        {
            fightRecord = GetFightRecord(atk, defTeam, atk.ProperSkill);
        }
        else
        {
            fightRecord = GetFightRecord(atk, defTeam, atk.NormalSkill);
        }
        fightRecord.BoutCount = BoutCount;
        FightRecords.Add(fightRecord);

        return IsEnd(atkTeam, defTeam);
    }

    private static FightRecordItem GetFightRecord(FightItem atk, FightItem[] defTeam, InitSkill atkSkill)
    {
        FightRecordItem fightRecord = new FightRecordItem();
        fightRecord.Atk = atk;
        if (atkSkill == null)
        {
            return fightRecord;
        }

        fightRecord.Skill = atkSkill;
        if (atkSkill.range == 0)
        {
            int defPos = GetDefPos(atk.Idx, defTeam);
            fightRecord.AtkEffectList.Add(GetAtkEffect(atk, defTeam[defPos], atkSkill));
        }
        else if (atkSkill.range == 1)
        {
            List<int> defPosList = GetRandomPos(defTeam);
            for (int i = 0; i < defPosList.Count; i++)
            {
                fightRecord.AtkEffectList.Add(GetAtkEffect(atk, defTeam[defPosList[i]], atkSkill));
            }
        }
        else
        {
            for (int i = 0; i < defTeam.Length; i++)
            {
                if (defTeam[i] != null && !defTeam[i].isDie())
                {
                    fightRecord.AtkEffectList.Add(GetAtkEffect(atk, defTeam[i], atkSkill));
                }
            }
        }

        for (int i=0; i<fightRecord.AtkEffectList.Count; i++)
        {
            if (fightRecord.AtkEffectList[i].eType != AtkEffectType.Dodge)
            {
                atk.MP += 10;
                if (atk.MP > 100)
                {
                    atk.MP = 100;
                }

                fightRecord.AtkMp = atk.MP;
                break;
            }
        }
        return fightRecord;
    }

    private static AtkEffect GetAtkEffect(FightItem atk, FightItem def, InitSkill atkSkill)
    {
        AtkEffect atkEffect = new AtkEffect();
        atkEffect.Target = def;
        if (IsHit(atk, def))
        {
            int damage = CountDamage(atk, def, atkSkill, out bool isBao);
            def.HP -= damage;
            if (def.HP < 0)
            {
                def.HP = 0;
            }

            atkEffect.eType = isBao ? AtkEffectType.LoseHpByBaoJi : AtkEffectType.LoseHp;
            atkEffect.Value = damage;
            atkEffect.CurrHp = def.HP;
            atkEffect.CurrMp = def.MP;
        }
        else
        {
            atkEffect.eType = AtkEffectType.Dodge;
            atkEffect.CurrHp = def.HP;
            atkEffect.CurrMp = def.MP;
        }
        return atkEffect;
    }

    private static int GetDefPos(int atkPos, FightItem[] defItems)
    {
        int defPos = DefaultRule[atkPos];
        if (defItems[defPos] == null || defItems[defPos].isDie())
        {
            for (int i = 0; i < defItems.Length; i++)
            {
                if (defItems[i] != null && !defItems[i].isDie())
                {
                    return i;
                }
            }

            return -1;
        }
        else
        {
            return defPos;
        }
    }

    private static List<int> GetRandomPos(FightItem[] defItems)
    {
        List<int> list = new List<int>();
        for (int i = 0; i < defItems.Length; i++)
        {
            if (defItems[i] != null && !defItems[i].isDie())
            {
                list.Add(i);
            }
        }
        int count = UnityEngine.Random.Range(2, 3);
        if (list.Count <= count)
        {
            return list;
        }
        else
        {
            for (int i = 0; i < list.Count; i++)
            {
                int idx = UnityEngine.Random.Range(0, list.Count - 1);
                int temp = list[idx];
                list[idx] = list[i];
                list[i] = temp;
            }

            int dif = list.Count - count;

            for (int i = 0; i < dif; i++)
            {
                list.RemoveAt(0);
            }

            return list;
        }
    }

    /// <summary>
    /// 是否命中
    /// </summary>
    private static bool IsHit(FightItem atk, FightItem def)
    {
        int value = atk.DEX - def.EVD;
        return UnityEngine.Random.Range(1, 10000) < value;
    }

    /// <summary>
    /// 是否暴击
    /// </summary>
    private static bool IsBaoJi(FightItem atk, FightItem def)
    {
        int value = atk.CRT - def.KBL;
        return UnityEngine.Random.Range(1, 10000) < value;
    }

    /// <summary>
    /// 计算伤害
    /// </summary>
    private static int CountDamage(FightItem atk, FightItem def, InitSkill skill, out bool isBao)
    {
        isBao = IsBaoJi(atk, def);

        int totalDamage = atk.ATK * skill.damage / 100;
        if (isBao)
        {
            totalDamage += totalDamage * 30 / 100;
        }
        
        int defValue = skill.damage_type == 0 ? def.DEF : def.RGS;

        totalDamage -= defValue;
        if (totalDamage < 0)
        {
            totalDamage = 1;
        }

        return totalDamage;
    }

    /// <summary>
    /// 是否结束
    /// </summary>
    private static bool IsEnd(FightItem[] atkItems, FightItem[] defItems)
    {
        bool rightIsZero = true;
        for (int i=0; i< atkItems.Length; i++)
        {
            if (atkItems != null)
            {
                if (!atkItems[i].isDie())
                {
                    rightIsZero = false;
                    break;
                }
            }
        }

        if (rightIsZero)
        {
            return true;
        }

        for (int i = 0; i < defItems.Length; i++)
        {
            if (defItems[i] != null)
            {
                if (!defItems[i].isDie())
                {
                    return false;
                }
            }
        }

        return true;
    }
}
